use chrono::{Duration as ChronoDuration, Utc};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport};
use notify::{RecursiveMode, Watcher, recommended_watcher};
use std::path::Path;
use std::sync::mpsc::channel;
use std::time::Duration;
use std::{fs, thread};

use std::sync::{Arc, Mutex};

// 防抖函数
fn debounce<F>(delay: Duration, f: F) -> impl Fn()
where
    F: Fn() + Send + Sync + 'static,
{
    // 使用 Arc 共享闭包
    let f = Arc::new(f);
    let last_time = Arc::new(Mutex::new(None));

    // 返回一个闭包，用于触发防抖函数
    move || {
        let f = Arc::clone(&f);
        let last_time = Arc::clone(&last_time);

        // 更新触发时间
        let now = Some(std::time::Instant::now());
        *last_time.lock().unwrap() = now;

        // 启动一个新线程来等待 delay 时间
        thread::spawn(move || {
            // 等待 delay 时间
            thread::sleep(delay);

            // 检查是否是最新的触发
            if let Some(time) = *last_time.lock().unwrap() {
                if time == now.unwrap() {
                    f();
                }
            }
        });
    }
}

#[tokio::main]
async fn main() {
    let path = "/home/dragon/project/natapp/bin/nohup.out"; // 替换为你的日志文件路径
    let (sender, receiver) = channel();

    // 创建文件监听器
    let mut watcher = recommended_watcher(sender).unwrap();

    // 监听文件变化
    watcher
        .watch(Path::new(path), RecursiveMode::NonRecursive)
        .unwrap();

    let last_trigger_time = Arc::new(Mutex::new(Utc::now() - ChronoDuration::minutes(10)));
    let last_trigger_time_clone = Arc::clone(&last_trigger_time);

    let debounce_send_mail = debounce(Duration::from_millis(500), move || {
        *last_trigger_time_clone.lock().unwrap() = Utc::now();
        if let Ok(last_line) = get_last_line(path) {
            if send_email(&last_line).is_ok() {
                println!("Email sent with last line: {}", last_line);
            } else {
                eprintln!("Failed to send email");
            }
        } else {
            eprintln!("Failed to read last line from log file");
        }
    });

    loop {
        if let Ok(_event) = receiver.recv() {
            let now = Utc::now();
            let last_trigger_time_clone = Arc::clone(&last_trigger_time);
            let duration_since_last_trigger = now - *last_trigger_time_clone.lock().unwrap();

            // 检查是否至少过了10分钟
            if duration_since_last_trigger.num_minutes() >= 10 {
                debounce_send_mail()
            }
        }
    }
}

// 获取文件的最后一行
fn get_last_line(path: &str) -> Result<String, std::io::Error> {
    let content = fs::read_to_string(path)?;
    let last_line = content.lines().last().unwrap_or("").to_string();
    Ok(last_line)
}

// 发送邮件
fn send_email(body: &str) -> Result<(), lettre::transport::smtp::Error> {
    let _email = Message::builder()
        .from("cstslswust@163.com".parse().unwrap())
        .to("cstslswust@163.com".parse().unwrap())
        .subject("Natapp 服务日志")
        .body(body.to_string())
        .unwrap();

    let creds = Credentials::new(
        "cstslswust@163.com".to_string(),
        "KNQ5M3AnG87fnvwy".to_string(),
    );

    let _mailer = SmtpTransport::relay("smtp.163.com")
        .unwrap()
        .credentials(creds)
        .build();

    // mailer.send(&email).unwrap();
    Ok(())
}
